﻿using FlashPay.DAO.Bank;
using FlashPay.DAO.Interface;
using FlashPay.DAO.Interface.Receipt;
using FlashPay.DAO.Sys;
using FlashPay.EF;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Enum;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Request.DepositMatchRecord;
using FlashPay.Entity.Response.Bank;
using FlashPay.Entity.Response.Company;
using FlashPay.Entity.Response.DepositMatchRecord;
using FlashPay.Entity.Response.Payment;
using FlashPay.Entity.Response.Sys;
using FlashPay.Service.Interface;
using FlashPay.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FlashPay.Service.Impl
{
    public class DepositMatchRecordServiceImpl : DepositMatchRecordService
    {
        /// <summary>
        /// 收款记录匹配接口
        /// </summary>
        private readonly DepositMatchRecordDAO _depositMatchRecordDao;

        /// <summary>
        /// 收款匹配规则
        /// </summary>
        private readonly DepositMatchRuleDao _depositMatchRuleDao;

        private readonly ReceiptDao _receive;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankInfoDAO _bankInfoDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        public DepositMatchRecordServiceImpl(DepositMatchRecordDAO depositMatchRecordDao, DepositMatchRuleDao depositMatchRuleDao, ReceiptDao receive,
            LogDao logDao, LogRecord logRecord, BankDao bankDao, CompanyDao companyDao, BankInfoDAO bankInfoDao, SysConfigDao sysConfigDao, FlashPayContext context)
        {
            this._depositMatchRecordDao = depositMatchRecordDao;
            this._depositMatchRuleDao = depositMatchRuleDao;
            this._receive = receive;
            this._logDao = logDao;
            this._logRecord = logRecord;
            this._bankDao = bankDao;
            this._companyDao = companyDao;
            this._bankInfoDao = bankInfoDao;
            this._sysConfigDao = sysConfigDao;
            this._context = context;
        }

        /// <summary>
        /// 获取收款匹配记录列表
        /// </summary>
        public DataGrid<DepositMatchRecordResponse> GetDepositMatchRecordList(DepositMatchRecordQuery query)
        {
            if (query.CompanyId.HasValue)
            {
                query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
                query.CompanyId = null;
            }
            return _depositMatchRecordDao.GetDepositMatchRecordList(query);
        }

        /// <summary>
        /// 根据ID查询详细信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public JResult<DepositMatchRecord> GetMatchRecordDetail(DepositMatchRecordQuery query)
        {
            var response = new JResult<DepositMatchRecord>()
            {
                Success = false
            };
            if (query == null)
            {
                response.ErrorMessage = "获取参数出错";
                return response;
            }
            try
            {
                var depositMatchRule = _depositMatchRecordDao.GetMatchRecordDetail(query);
                response.Success = true;
                response.Data = depositMatchRule;
            }
            catch (Exception ex)
            {
                response.ErrorMessage = "服务器错误";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.DepositMatchRecord_Detail, query, "查询规则详细信息出错:" + ex.Message);
            }
            return response;
        }

        /// <summary>
        /// 收款记录查询(规则)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public DataGrid<DepositRecordResponse> GetMatchSearch(GetMatchSearchRequest request)
        {
            //输出
            var response = new DataGrid<DepositRecordResponse>() {
                Success = false
            };

            try
            {
                //获取收款匹配记录(编号)
                var depositMatchRecord = _depositMatchRecordDao.GetDepositMatchRecord(request.Id);
                if (depositMatchRecord == null)
                {
                    return new DataGrid<DepositRecordResponse>()
                    {
                        Success = false,
                        ErrorMessage = "收款匹配记录不存"
                    };
                }

                //获取匹配规则(公司、银行编码、转款类型)
                var depositMatchRule = _depositMatchRuleDao.GetRuleByCompanyId(new DepositMatchRule()
                {
                    CompanyId = depositMatchRecord.CompanyId,
                    MatchBankCode = depositMatchRecord.BankCode,
                    MatchTranstype = depositMatchRecord.Transtype.ToString()
                });

                if (depositMatchRule == null) {
                    return new DataGrid<DepositRecordResponse>()
                    {
                        Success = false,
                        ErrorMessage = "请先到\"收款匹配规则\"建立匹配规则！"
                    };
                }

                //收款查询参数
                var depositRecordQuery = new DepositRecordQuery();
                depositRecordQuery.DepositMatchID = request.Id;
                depositRecordQuery.BankCode = depositMatchRecord.BankCode;
                depositRecordQuery.CompanyIds = new List<int>
                {
                    depositMatchRecord.CompanyId
                };

                var startTime = depositMatchRecord.DepositDate;
                if (depositMatchRule.MatchMinusMinute < 0) {
                    startTime.AddMinutes(depositMatchRule.MatchMinusMinute);
                }
                //时期
                if (request.Minutes.HasValue && request.Minutes.Value > 0) {
                    depositRecordQuery.StartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss");
                    depositRecordQuery.EndTime = depositMatchRecord.DepositDate.AddMinutes(request.Minutes.Value).ToString("yyyy-MM-dd HH:mm:ss");
                } else if (request.Minutes.HasValue && request.Minutes.Value < 0) {
                    depositRecordQuery.StartTime = startTime.AddMinutes(request.Minutes.Value).ToString("yyyy-MM-dd HH:mm:ss");
                    depositRecordQuery.EndTime = depositMatchRecord.DepositDate.ToString("yyyy-MM-dd HH:mm:ss");
                } else {
                    depositRecordQuery.StartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss");
                    depositRecordQuery.EndTime = depositMatchRecord.DepositDate.AddMinutes(depositMatchRule.MatchMinute).ToString("yyyy-MM-dd HH:mm:ss");
                }
                //存款类型
                if (!string.IsNullOrEmpty(depositMatchRule.MatchTranstype) && !request.MatchTranstype.HasValue)
                {
                    if (depositMatchRecord.Transtype.HasValue)
                    {
                        depositRecordQuery.TransTypeList = new List<int>() { depositMatchRecord.Transtype.Value };
                    }
                    else {
                        depositRecordQuery.TransTypeList = depositMatchRule.MatchTranstype.Split(",").ToList().Select(c => int.Parse(c)).ToList();
                    }
                }
                //匹配规则
                //不匹配：2019-03-19新增需求
                //1、交易类型
                //2、客户姓名
                #region 匹配规则
                var matchRuleArray = depositMatchRule.MatchRule.Split(',').ToList();
                if (matchRuleArray != null && matchRuleArray.Any())
                {
                    //客户姓名
                    if (matchRuleArray.Contains("1") && !string.IsNullOrEmpty(depositMatchRecord.ClientAccountName) && !request.MatchClientAccountName.HasValue)
                    {
                        depositRecordQuery.WithdrawalAccountName = depositMatchRecord.ClientAccountName;
                    }
                    //金额
                    if (matchRuleArray.Contains("2") && depositMatchRecord.DepositAmount>0 && !request.MatchBalance.HasValue)
                    {
                        depositRecordQuery.DepositAmount = depositMatchRecord.DepositAmount;
                    }
                    //客户卡号
                    if (matchRuleArray.Contains("3") && !string.IsNullOrEmpty(depositMatchRecord.ClientCardNumber))
                    {
                        depositRecordQuery.WithdrawalCardNumber = depositMatchRecord.ClientCardNumber;
                    }
                    //附言
                    if (matchRuleArray.Contains("4") && !string.IsNullOrEmpty(depositMatchRecord.PostScript))
                    {
                        depositRecordQuery.PostScript = WebUtil.ToDBC(depositMatchRecord.PostScript);
                    }
                    //收款卡号
                    if (matchRuleArray.Contains("5") && !string.IsNullOrEmpty(depositMatchRecord.DepositCardNumber)) {
                        if (string.IsNullOrEmpty(depositMatchRecord.DepositCardNumber))
                        {
                            depositRecordQuery.DepositCardID = -1;
                        }
                        else {
                            var bankCard = _bankDao.GetBcInfo(depositMatchRecord.DepositCardNumber);
                            if (bankCard != null){
                                depositRecordQuery.DepositCardID = bankCard.Bcid;
                            }
                            else
                            {
                                depositRecordQuery.DepositCardID = -1;
                            }
                        }
                    }
                }
                #endregion

                return _receive.GetMatchDepositRecord(depositRecordQuery);
            }
            catch (Exception ex) {
                response.ErrorMessage = "服务器错误:" + ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 根据规则信息查询收款记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<DepositOrPaymentRecordResponse> GetRecordListByRuleInfo(DepositMatchRecordQuery query)
        {
            var response = new PagedList<DepositOrPaymentRecordResponse>()
            {
                Success = false
            };
            if (query == null)
            {
                response.ErrorMessage = "获取参数出错";
                return response;
            }

            try
            {
                //查询详细信息，得到companyId、Bankcode、depositDate....
                var depositMatchRecord = _depositMatchRecordDao.GetMatchRecordDetail(query);
                if (depositMatchRecord != null)
                {
                    #region 详细信息
                    int companyId = depositMatchRecord.CompanyId;
                    string bankCode = depositMatchRecord.BankCode;
                    DateTime depositDate = depositMatchRecord.DepositDate;//订单时间
                    string clientAccountName = depositMatchRecord.ClientAccountName;//用户名称
                    decimal depositAmount = depositMatchRecord.DepositAmount;//金额
                    //string depositMatchID = depositMatchRule.Id.ToString();//详细ID
                    string postScript = depositMatchRecord.PostScript;//客户附言
                    string clientCardNumber = depositMatchRecord.ClientCardNumber;//客户卡号
                    string depositCardNumber = depositMatchRecord.DepositCardNumber;//收款卡号
                    #endregion

                    #region
                    //根据companyId、Bankcode查出规则信息
                    //var ruleInfo = _depositMatchRuleDao.GetRuleByCompanyId(companyId, bankCode);
                    //之前（没有根据存款类型这个条件）现在加上
                    var ruleInfo = _depositMatchRuleDao.GetRuleByCompanyId(new DepositMatchRule() {
                        CompanyId = companyId,
                        MatchBankCode = bankCode,
                        MatchTranstype = depositMatchRecord.Transtype.ToString()
                    });
                    #endregion

                    if (ruleInfo.Id >0)
                    {
                        int matchMinute = ruleInfo.MatchMinute;
                        if (query.MatchMinutes >= -1440 && query.MatchMinutes <= 1440 && query.MatchMinutes!=0)
                        {
                            matchMinute = query.MatchMinutes;
                        }

                        #region 搜索收款记录
                        //根据规则信息——depositDate加上matchMinute时间区间 、companyId、Bankcode作为筛选条件
                        PaymentRecordQuery q = new PaymentRecordQuery();

                        if (matchMinute > 0)
                        {
                            q.StartTime = depositDate.ToString("yyyy-MM-dd HH:mm:ss");
                            q.EndTime = depositDate.AddMinutes(matchMinute).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            q.StartTime = depositDate.AddMinutes(matchMinute).ToString("yyyy-MM-dd HH:mm:ss");
                            q.EndTime = depositDate.ToString("yyyy-MM-dd HH:mm:ss");
                        }

                        q.BankCode = bankCode;
                        q.CompanyIds = new List<int> { companyId };
                        q.Type = 1;

                        string matchRule = ruleInfo.MatchRule;
                        if (!string.IsNullOrEmpty(matchRule))
                        {
                            if (matchRule.IndexOf("1") > -1)
                            {
                                q.WithdrawalAccountName = clientAccountName;//客户姓名
                            }
                            //是否不匹配金额
                            if (!query.IsBalance)
                            {
                                if (matchRule.IndexOf("2") > -1)
                                {
                                    q.DepositAmount = depositAmount;//金额
                                }
                            }
                            //匹配收款卡号
                            if (matchRule.IndexOf("5") > -1)
                            {
                                if (string.IsNullOrEmpty(depositCardNumber))
                                {
                                    q.DepositCardID = -1;
                                }
                                else
                                {
                                    BankCard bc = _bankDao.GetBcInfo(depositCardNumber);
                                    if (bc != null)
                                    {
                                        q.DepositCardID = bc.Bcid;
                                    }
                                    else
                                    {
                                        q.DepositCardID = -1;
                                    }
                                }
                            }
                        }

                        //存款类型
                        if (!string.IsNullOrEmpty(ruleInfo.MatchTranstype))
                        {
                            q.TransTypeList = ruleInfo.MatchTranstype.Split(",").ToList().Select(e=>int.Parse(e)).ToList();
                        }

                        //收款记录列表
                        q.Page = 1;
                        q.Rows = 20;

                        PagedList<DepositOrPaymentRecordResponse> pList = _receive.GetReceiptRecordList(q);
                        IList<DepositOrPaymentRecordResponse> list = pList.TData;
                        #endregion

                        #region 匹配卡号、附言
                        bool isSelectMatch = false;//是否勾选了卡号或附言
                        List<DepositOrPaymentRecordResponse> newList = new List<DepositOrPaymentRecordResponse>();
                        //判断卡号、附言是否有勾选
                        if (matchRule.IndexOf("3") > -1 || matchRule.IndexOf("4") > -1)
                        {
                            if (pList.Success && pList.TotalCount > 0 && list != null)
                            {
                                isSelectMatch = true;

                                for (int i = 0; i < list.Count; i++)
                                {
                                    var lCardNumber = list[i].WithdrawalCardNumber;//CardNumber
                                    string lPostScript = list[i].PostScript;

                                    bool isMatch3 = CheckMatch(matchRule,"3", lCardNumber);
                                    bool isMatch4 = CheckMatch(matchRule, "4", lPostScript);

                                    if (isMatch3 && isMatch4)
                                    {
                                        if (CheckCardNoMatch(lCardNumber,clientCardNumber) && lPostScript == postScript) 
                                        {
                                            newList.Add(list[i]);
                                        }
                                    }
                                    //卡号判断前四位、后四位是否匹配
                                    else if (isMatch3)
                                    {
                                        if (CheckCardNoMatch(lCardNumber, clientCardNumber))
                                        {
                                            newList.Add(list[i]);
                                        }
                                    }
                                    //附言判断是否相等
                                   else if (isMatch4)
                                    {
                                        if (lPostScript == postScript)
                                        {
                                            newList.Add(list[i]);
                                        }
                                    }
                                }
                            }
                        }
                        #endregion 匹配卡号、附言

                        if (!isSelectMatch)
                        {
                            response.TData = list;
                            response.TotalCount = list.Count;
                        }
                        else
                        {
                            response.TData = newList;
                            response.TotalCount = newList.Count;
                        }
                        response.Success = true;
                        response.StatusCode = matchMinute.ToString();
                    }
                    else
                    {
                        response.ErrorMessage = "请先到\"收款匹配规则\"建立匹配规则！";
                    }
                }
                else
                {
                    response.ErrorMessage = "未获取到详细信息";
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = "服务器错误";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.DepositMatchRecord_Detail, query, "根据规则信息查询收款记录:" + ex.Message);
            }
            return response;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        private List<CompanyResponse> GetCompany(int companyId, int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus = item.CompanyStatus
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 获取收款匹配记录
        /// </summary>
        public JResult<DepositMatchRecordAddResponse> GetDepositMatchRecordAdd(DepositMatchRecordAddRequest request)
        {
            var depositMatchRecordResponse = new DepositMatchRecordAddResponse();

            var companyList = GetCompany(request.CompanyId, 2);

            if (companyList != null && companyList.Any())
            {
                depositMatchRecordResponse.CompanyResponse = companyList;
            }

            #region 银行信息
            var bankinfoList = _bankInfoDao.GetBankInfoList();

            var bankinfoResponse = new List<BankInfoResponse>();

            if (bankinfoList != null)
            {
                foreach (var item in bankinfoList)
                {
                    bankinfoResponse.Add(new BankInfoResponse()
                    {
                        BankCode = item.BankCode,
                        BankName = item.BankName
                    });
                }

                depositMatchRecordResponse.BankInfoResponse = bankinfoResponse;
            }
            #endregion

            #region 交易类型
            var transtype = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "Transtype" });
            if (transtype != null && transtype.Any())
            {
                var sysConfigResponse = new List<SysConfigResponse>();

                transtype.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse()
                    {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                depositMatchRecordResponse.Transtypes = sysConfigResponse;
            }
            #endregion

            #region 付款类型
            var paymenttype = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
            if (paymenttype != null && paymenttype.Any())
            {
                var sysConfigResponse = new List<SysConfigResponse>();

                paymenttype.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse()
                    {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                depositMatchRecordResponse.Paytype = sysConfigResponse;
            }
            #endregion

            //新增按钮权限
            if (request.UserPermission.Contains("ReceiptMatchList007"))
            {
                depositMatchRecordResponse.AddPermission = "ReceiptMatchList007";
            }

            return new JResult<DepositMatchRecordAddResponse>() {
                Success = true,
                Data = depositMatchRecordResponse
            };
        }

        /// <summary>
        /// 获取收款匹配记录
        /// </summary>
        public JResult<DepositMatchRecordAddResponse> GetDepositMatchRecordById(DepositMatchRecordAddRequest request)
        {
            var depositMatchRecordResponse = new DepositMatchRecordAddResponse();

            var companyList = GetCompany(request.CompanyId, 2);

            if (companyList != null && companyList.Any())
            {
                depositMatchRecordResponse.CompanyResponse = companyList;
            }

            #region 银行信息
            var bankinfoList = _bankInfoDao.GetBankInfoList();

            var bankinfoResponse = new List<BankInfoResponse>();

            if (bankinfoList != null)
            {
                foreach (var item in bankinfoList)
                {
                    bankinfoResponse.Add(new BankInfoResponse()
                    {
                        BankCode = item.BankCode,
                        BankName = item.BankName
                    });
                }

                depositMatchRecordResponse.BankInfoResponse = bankinfoResponse;
            }
            #endregion

            #region 交易类型
            var transtype = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "Transtype" });
            if (transtype != null && transtype.Any())
            {
                var sysConfigResponse = new List<SysConfigResponse>();

                transtype.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse()
                    {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                depositMatchRecordResponse.Transtypes = sysConfigResponse;
            }
            #endregion

            #region 付款类型
            var paymenttype = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
            if (paymenttype != null && paymenttype.Any())
            {
                var sysConfigResponse = new List<SysConfigResponse>();

                paymenttype.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse()
                    {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                depositMatchRecordResponse.Paytype = sysConfigResponse;
            }
            #endregion

            var depositMatchRecord = _context.DepositMatchRecord.FirstOrDefault(c => c.Id == request.Id);
            if (depositMatchRecord != null) {
                depositMatchRecordResponse.Id = depositMatchRecord.Id.ToString();
                depositMatchRecordResponse.CompanyId = depositMatchRecord.CompanyId;
                depositMatchRecordResponse.BankCode = depositMatchRecord.BankCode;
                depositMatchRecordResponse.MatchOrderNo = depositMatchRecord.MatchOrderNo;
                depositMatchRecordResponse.ClientOrderNo = depositMatchRecord.ClientOrderNo;
                depositMatchRecordResponse.DepositCardNumber = depositMatchRecord.DepositCardNumber;
                depositMatchRecordResponse.DepositRemark = depositMatchRecord.DepositRemark;
                depositMatchRecordResponse.CreateDbdate = depositMatchRecord.CreateDbdate;
                depositMatchRecordResponse.DepositDate = depositMatchRecord.DepositDate;
                depositMatchRecordResponse.DepositAmount = depositMatchRecord.DepositAmount;
                depositMatchRecordResponse.ClientBankName = depositMatchRecord.ClientBankName;
                depositMatchRecordResponse.ClientAccountName = depositMatchRecord.ClientAccountName;
                depositMatchRecordResponse.ClientCardNumber = depositMatchRecord.ClientCardNumber;
                depositMatchRecordResponse.PostScript = depositMatchRecord.PostScript;
                depositMatchRecordResponse.Transtype = depositMatchRecord.Transtype;
                depositMatchRecordResponse.Status = depositMatchRecord.Status;
                depositMatchRecordResponse.UpdateId = depositMatchRecord.UpdateId;
                depositMatchRecordResponse.UpdateDate = depositMatchRecord.UpdateDate;
            }
            //新增按钮权限
            if (request.UserPermission.Contains("ReceiptMatchList007"))
            {
                depositMatchRecordResponse.AddPermission = "ReceiptMatchList007";
            }

            return new JResult<DepositMatchRecordAddResponse>() {
                Success = true,
                Data = depositMatchRecordResponse
            };
        }

        //判断卡号是否匹配
        private bool CheckCardNoMatch(string lCardNumber,string clientCardNumber)
        {
            bool isMatch = false;

            if (string.IsNullOrEmpty(clientCardNumber) || string.IsNullOrEmpty(lCardNumber)) return isMatch;

            DepositOrPaymentRecordResponse dpr = new DepositOrPaymentRecordResponse();
            if (lCardNumber.Substring(0, 4).Equals(clientCardNumber.Substring(0, 4)) &&
                    lCardNumber.Substring(lCardNumber.Length - 4, 4)
                        .Equals(clientCardNumber.Substring(
                            clientCardNumber.Length - 4, 4)))
            {
                isMatch = true;
            }
            return isMatch;
        }

        //判断匹配规则和字符串匹配结果
        private bool CheckMatch(string matchRule,string type,string str)
        {
            bool isMatch = matchRule.Contains(type) && !string.IsNullOrEmpty(str);
            return isMatch;
        }

        /// <summary>
        /// 收款匹配记录[绑定收款记录]
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult ReceiptMatchRecordBindReceiptRecord(ReceiptMatchRecordBindReceiptRecordRequest request)
        {
            var response = new JResult<DepositMatchRecord>()
            {
                Success = false
            };
            if (request.Id.ToString() == null || request.OrderNo == null)
            {
                response.ErrorMessage = "获取参数出错";
                return response;
            }
            try
            {
                var dRows = _depositMatchRecordDao.ReceiptMatchRecordBindReceiptRecord(request);
                if (dRows > 0)
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.DepositMatchRecord_MakeUp.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"收款匹配记录【手动】匹配成功,收款匹配订单号:{request.Id},收款记录订单号:{request.OrderNo}";
                    _logDao.Insert(_logRecord);

                    response.Success = true;
                    response.SuccessMessage = "匹配成功";
                }
                else if (dRows == 0)
                {
                    response.ErrorMessage = "请勿重新匹配";
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = "服务器错误";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.DepositMatchRecord_Set, request, "设置规则匹配出错:"+ex.Message);
            }
            return response;
        }

        //记录日志
        public void AddLog(sbyte level, int type, Object data, string remark)
        {
            _logRecord.LogLevel = level;
            _logRecord.LogType = type;
            _logRecord.CreateDate = DateTime.Now;
            _logRecord.LogRemark = remark;
            _logRecord.RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            _logDao.Insert(_logRecord);
        }

        /// <summary>
        /// 新增收款匹配记录
        /// </summary>
        /// <param name="request"></param>
        public JResult Add(AddRequest request)
        {
            return _depositMatchRecordDao.Add(request);
        }

        public JResult Edit(EditRequest request)
        {
            var response = new JResult() 
            { 
                Success = false
            };

            try
            {
                //收款卡号
                if (string.IsNullOrEmpty(request.BankCode))
                {
                    throw new Exception("收款银行编码不能为空");
                }
                //收款卡号
                if (!string.IsNullOrEmpty(request.DepositCardNumber))
                {
                    var documentNumberReg = new Regex(@"^.{10,20}$");
                    if (!documentNumberReg.IsMatch(request.DepositCardNumber))
                    {
                        throw new Exception("收款卡号必须介于 10 和 20 之间");
                    }
                }

                //存款金额
                var depositAmountReg = new Regex(@"^(([1-9]\d{0,3})|0)(?:\.[0-9]{1,4})?$");
                if (!depositAmountReg.IsMatch(request.DepositAmount.ToString()))
                {
                    throw new Exception("存款金额最大保留四位小数，整数最多保留四位");
                }

                //跨行转账
                if (!request.Transtype.HasValue)
                {
                    throw new Exception("请选择交易类型！");
                }

                var depositMatchRecord = _context.DepositMatchRecord.FirstOrDefault(c => c.Id == long.Parse(request.Id));
                if (depositMatchRecord != null)
                {
                    depositMatchRecord.BankCode = request.BankCode;
                    depositMatchRecord.DepositCardNumber = request.DepositCardNumber;
                    depositMatchRecord.DepositDate = DateTime.Parse(request.DepositDate);


                    depositMatchRecord.DepositAmount = decimal.Parse(request.DepositAmount);
                    depositMatchRecord.ClientAccountName = request.ClientAccountName;
                    depositMatchRecord.ClientCardNumber = request.ClientCardNumber;
                    depositMatchRecord.Transtype = request.Transtype.Value;
                    depositMatchRecord.PostScript = request.PostScript;

                    _context.Entry<DepositMatchRecord>(depositMatchRecord);
                    _context.SaveChanges();

                    response.Success = true;
                    response.SuccessMessage = "修改成功";
                }
            }
            catch (Exception ex) {
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
    }
}
